package com.chj.comp.common.auth.security.config;

import com.chj.comp.common.auth.security.handler.FailureHandler;
import com.chj.comp.common.auth.security.handler.LogoutHandler;
import com.chj.comp.common.auth.security.handler.SuccessHandler;
import com.chj.comp.common.core.constant.CommonConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Description:
 * @Author: cuihui
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SuccessHandler successHandler;

    @Autowired
    private FailureHandler failureHandler;

    @Autowired
    private LogoutHandler logoutHandler;

    /**
     * 配置用户密码加密规则
     * {@link com.chj.comp.common.help.util.SecurityPwdUtil#encodeStr}
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 请求拦截处理
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 禁用跨域防护
            .csrf().disable()
            //启用基本登录功能
            .formLogin()
            // 登录页面的访问路径-无限制
            .loginPage("/oauth/login").permitAll()
            // 登录页面的提交路径，和自定义页面base-login.html中action保持一致）
            .loginProcessingUrl(CommonConstant.LOGIN_URI).permitAll()
            // 登陆成功的回调函数-无限制（此处注释掉，登录成功后默认跳转授权页面）
//            .successHandler(successHandler).permitAll()
            // 登陆失败的回调函数-无限制
            .failureHandler(failureHandler).permitAll()
            // 登出成功回调函数
            .and().logout().logoutSuccessHandler(logoutHandler)
            // 允许基于使用HttpServletRequest限制访问
            .and().authorizeRequests()
            // 所有访问url-无限制
            .antMatchers("/**").permitAll();
    }
}
